# @Data  : 2019/11/29 14:28
# @Author: 
# @File  : FwVariables.py
import os
import platform
import random
import time

from Lib import constants
from Lib.zcm.const import prompt
from Lib.zcm.assistant import FwConfigUtils
from robot.api import logger

from Lib.zcm.utils.encryptor import EncryptUtil

config = FwConfigUtils.FwConfigUtils.get_handle()
all_sections = config.sections()


def get_value(section, option, default=None):
    '''
    获取config参数的公共方法
    :param section:
    :param option:
    :param default:
    :return:
    '''
    try:
        res = config.get(section, option)
        res = EncryptUtil.decrypt_string(res)
    except:
        logger.debug('section {section} option {option} not define, return default {default}'.format(section=section,
                                                                                                     option=option,
                                                                                                     default=default))
        return default
    else:
        return res


def get_bool_value(section, option, default=None):
    '''
    获取config参数的公共方法
    :param section:
    :param option:
    :param default:
    :return:
    '''
    try:
        res = config.getboolean(section, option)
    except:
        logger.debug('section {section} option {option} not define, return default {default}'.format(section=section,
                                                                                                     option=option,
                                                                                                     default=default))
        return default
    else:
        return res


def get_api_module(link_name):
    '''
    获取连接数据库的api module
    :param link_name:
    :return:
    '''
    assert link_name in all_sections, prompt.DB['nameErr']
    return get_value(link_name, "apiModule")


def get_sftp_host(link_name):
    '''
    获取ftp host
    '''
    assert link_name in all_sections, prompt.DB['nameErr']
    return get_value(link_name, "host")


def get_remote_host(link_name):
    '''
    获取目标主机的 host
    '''
    assert link_name in all_sections, prompt.DB['nameErr']
    return get_value(link_name, "host")


def get_sftp_user(link_name):
    '''
    获取ftp user
    '''
    assert link_name in all_sections, prompt.DB['nameErr']
    return get_value(link_name, "user")


def get_remote_user(link_name):
    '''
    获取目标主机的 user
    '''
    assert link_name in all_sections, prompt.DB['nameErr']
    return get_value(link_name, "user")


def get_sftp_password(link_name):
    '''
    获取ftp password
    '''
    assert link_name in all_sections, prompt.DB['nameErr']
    return get_value(link_name, "password")


def get_remote_password(link_name):
    '''
    获取目标主机的 password
    '''
    assert link_name in all_sections, prompt.DB['nameErr']
    return get_value(link_name, "password")


def get_remote_timeout(link_name):
    '''
    获取超时时间
    '''
    assert link_name in all_sections, prompt.DB['nameErr']
    return int(get_value(link_name, "time_out", 5))


def get_sftp_port(link_name):
    '''
    获取ftp port
    '''
    assert link_name in all_sections, prompt.DB['nameErr']
    return int(get_value(link_name, "port"))


def get_remote_port(link_name):
    '''
    获取目标主机的 port
    '''
    assert link_name in all_sections, prompt.DB['nameErr']
    return int(get_value(link_name, "port"))


def get_sftp_home_dir(link_name):
    '''
    获取ftp home_dir
    '''
    assert link_name in all_sections, prompt.DB['nameErr']
    return get_value(link_name, "home_dir", "")


def get_startup_nodes(link_name):
    """
    获取redis集群信息
    """
    assert link_name in all_sections, prompt.DB['nameErr']
    return get_value(link_name, "startup_nodes")


def get_olc_host(link_name):
    # 获取olc host
    assert link_name in all_sections, prompt.DB['nameErr']
    return get_value(link_name, "host")


def get_dcc_rec_time_out(link_name):
    # 获取dcc响应超时时间
    assert link_name in all_sections, prompt.DB['nameErr']
    return get_value(link_name, "time_out", 30)


def get_dcc_project_code():
    # 获取dcc的project_code
    # 约定section名称固定为COMMON
    dcc_project_code_link_name = "COMMON"
    # 如果没有配置，则返回默认值def
    return get_value(dcc_project_code_link_name, "host", "def")


def get_dcc_avpfile_path(link_name):
    # 获取avpfile目录
    assert link_name in all_sections, prompt.DB['nameErr']
    return get_value(link_name, "avpfile_path", "avpfile")


def get_olc_port(link_name):
    # 获取olc port
    assert link_name in all_sections, prompt.DB['nameErr']
    return get_value(link_name, "port")


# dubbo相关配置
# zk地址
def get_zk_address(link_name):
    # zk地址
    assert link_name in all_sections, prompt.DUBBO['nameErr']
    return get_value(link_name, "zookeeper")


def get_registry_group(link_name):
    # 注册分组
    assert link_name in all_sections, prompt.DUBBO['nameErr']
    return get_value(link_name, "registry_group")


def get_post_dubbo_time_out(link_name):
    # 请求dubbo超时时间
    assert link_name in all_sections, prompt.DUBBO['nameErr']
    return int(get_value(link_name, "time_out", 300))


def get_dubbo_test_url():
    # 获取dubbo测试地址
    return os.getenv('DUBBO_TEST_URL', "https://dev.iwhalecloud.com:25000/portal/zcm-cloudtest/dubbo/test")


def get_task_id():
    from Lib.constants import DEFAULT_TASK_ID
    # 获取taskid
    return os.getenv('TASKID', DEFAULT_TASK_ID)


def get_origin_host():
    # 获取
    return "SCP${}.chinatelecom.com".format(get_task_id())


def get_db_url(link_name):
    '''
    获取config.ini中配置的数据库url
    :param link_name:
    :return:
    '''
    assert link_name in all_sections, prompt.DB['nameErr']
    return get_value(link_name, "url")


def get_qmdb_version(link_name):
    '''
    获取config.ini中配置的qmdb版本，默认V9
    :param link_name:
    :return:
    '''
    assert link_name in all_sections, prompt.DB['nameErr']
    return get_value(link_name, "version", "V9")


def get_db_language(link_name):
    '''
    获取config.ini中配置的数据库语言，默认None
    :param link_name:
    :return:
    '''
    assert link_name in all_sections, prompt.DB['nameErr']
    return get_value(link_name, "language", None)


def get_wait_time():
    '''
    获取系统级别的等待时间，若未配置该参数，默认返回10
    :return:
    '''
    return get_value("GENERAL", "WAIT_TIME", '10')


def get_ignore_error():
    '''
    是否忽略错误。不抛错直接返回执行结果，由用户自行解析判断。（目前仅作用于ZHttpRunTest）
    :return:
    '''
    return get_bool_value("GENERAL", "IGNORE_ERROR", False)


def get_headless_mode():
    '''
    是否在单容器中运行
    :return:
    '''
    return get_value("GENERAL", "HEADLESS_MODE", False) or os.getenv('HEADLESS_MODE', "False").lower() == 'true'


def isPicture():
    '''
    获取截图开关，True为需要截图，False不需要截图，如果没有配置该参数，默认返回False
    :return:
    '''
    return get_bool_value("isPicture", "isPicture", False)


def get_version():
    '''
    获取crm版本信息，若未配置该参数，默认返回V9
    :return:
    '''
    return get_value("GENERAL", "VERSION", 'V9').upper()


def get_driver():
    """
    获取驱动
    :return:
    """
    return get_value("GENERAL", "DRIVER", 'chrome')


def get_cfg_name():
    '''
    获取config的名称
    :return:
    '''
    return FwConfigUtils.cfgName


def get_ef_name():
    '''
    获取自定义保存异常文件名称， 默认未errs.txt
    :return:
    '''
    return get_value("GENERAL", "EF_NAME", 'errs.txt')


def get_url():
    '''
    获取url
    :return:
    '''
    return get_value('ENV', 'url', "http://172.16.25.92/portal-web/")


def get_env_user():
    '''
    获取登陆门户用户名称
    :return:
    '''
    return get_value('ENV', 'loginUser', 'admin')


def get_env_pwd():
    '''
    获取登陆门户密码
    :return:
    '''
    return get_value('ENV', 'loginPwd', 'Uportal_123')


def get_project_code():
    """
    获取project
    :return:
    """
    return FwConfigUtils.project_code


def get_project_code_default():
    """
    获取默认project_code
    :return:
    """
    return FwConfigUtils.project_code_default


def get_case_root():
    '''

    :return: 返回case的根路径
    '''
    return FwConfigUtils.case_path


def get_env_language():
    '''
    获取本地化语言，默认中文
    :return: zh,en
    '''
    return get_value('GENERAL', 'LANGUAGE', 'zh')


def get_wait_time_out():
    """
    获取超时时间
    :return:
    """
    timeout = get_value('GENERAL', 'WAIT_TIME_OUT', '60')
    return int(timeout)


def get_block_times():
    """
    获取检测blockui的次数
    :return:
    """
    return get_value('BlockUI', 'times', '3')


def get_block_interval():
    """
    获取检测blockui的时间间隔
    :return:
    """
    return get_value('BlockUI', 'interval', '2')


def ui_proxy_server_bin_path():
    '''
    前台页面，请求耗时上线， 毫秒
    :return:
    '''
    if _is_run_in_container():
        # 如果在容器中运行，直接使用容器内置的代理
        return '/home/seluser/zcm-cloudtest-agent/dep/browsermob-proxy-2.1.4/bin/browsermob-proxy'
    return get_value('UI', 'INTERCEPT_SERVER_BIN_PATH',
                     '/home/seluser/zcm-cloudtest-agent/dep/browsermob-proxy-2.1.4/bin/browsermob-proxy')


def is_intercept_ui_request():
    '''
    是否拦截 UI 请求，分析har数据
    :return:
    '''
    return get_bool_value('UI', 'INTERCEPT_REQUEST', False)


def ui_request_cost_thread():
    '''
    前台页面，请求耗时上线， 毫秒
    :return:
    '''
    try:
        value = int(get_value('UI', 'INTERCEPT_REQUEST_TIME_COST_THREAD', 500))
    except:
        value = 500
    return value


def _is_run_in_container():
    '''
    是否在容器中运行
    '''
    if os.getenv('CALLBACK_URL', None) is not None:
        return True
    return False


# zdaas相关配置
def get_zdaas_url():
    """
    获取zdaas url
    :return:
    """
    return get_value('zdaas', 'proxy_url', '192.168.50.128:8082')


def get_zdaas_auth():
    """
    获取zdaas代理鉴权用户名
    :return:
    """
    return get_value('zdaas', 'authorization', 'Basic emRhYXM6MWppYW44U2h1KQ==')


# open api相关
def get_api_addr():
    """
    获取config中api地址
    :return:
    """
    return get_value('ENV', 'openapi')


def is_open_itracing_code_cover_collector():
    return os.getenv(constants.ENV_ZCM_CODE_COV_COLLECT_MODE, '0') == '2'


def is_open_collect_single_case_code_cover():
    return os.getenv(constants.ENV_ZCM_CODE_COV_SINGLE_CASE_SWITCH, 'FALSE').lower() == 'true'


def case_http_proxy_header_key_variable():
    return '${zcm.case_http_proxy_header_key}'


def case_http_proxy_header_value_variable():
    return '${zcm.case_http_proxy_header_value}'


def case_http_proxy_header_key_variable_value():
    return 'BUSINESS_ID'
